package com.feihong.yw189.bluetooth.bleutils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.format.DateFormat;
import android.util.Base64;
import android.util.Log;

import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.bean.Data;
import com.feihong.yw189.bluetooth.bean.IdInfo;
import com.feihong.yw189.bluetooth.listener.UpLoadListener;
import com.feihong.yw189.bluetooth.utils.util.BitmapAndStringUtils;
import com.feihong.yw189.bluetooth.utils.util.PrefUtils;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.google.gson.Gson;

import org.xutils.common.Callback;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Locale;


/**
 * 2017/8/24
 * 上传信息工具类
 * 返回成功失败监听
 */

public class BleHttpUtils {

    // 注册成功失败监听
    private UpLoadListener mOnUpLoadListener;
    private String filePhoto, id_icon, idPath;
    private Activity mContext;
    private String bluetoothName = "";
    private Bitmap photo = null;
    private Boolean mFlag = false; // 补卡还是读卡

    private String name, sex, nation, id_num, address, sign_office, photoHeard, to, from, born;
    private String birth_year, birth_month, birth_day, sign_data;

    public BleHttpUtils(Context context, String bluetoothName, Boolean flag, UpLoadListener mOnUpLoadListener) {
        this.mContext = (Activity) context;
        this.bluetoothName = bluetoothName;
        this.mFlag = flag;
        this.mOnUpLoadListener = mOnUpLoadListener;
    }

    /**
     * 上传身份证信息
     */
    public void upLoadSfzPhoto(String bleNum, String bleId, String maddress, String mphotoHeard, String msex, String mid_num,
                               String mnation, String msign_office, String mto, String mname,
                               String mfrom, String mborn, String msign_data, String mbirth_year,
                               String mbirth_month, String mbirth_day, Bitmap mphoto) {
        this.photo = mphoto;
        this.address = maddress.replaceAll(" ", "");
        this.to = mto.replaceAll(" ", "");
        this.from = mfrom.replaceAll(" ", "");
        this.born = mborn.replaceAll(" ", "");
        this.photoHeard = mphotoHeard.replaceAll(" ", "");
        this.sex = msex.replaceAll(" ", "");
        this.id_num = mid_num.replaceAll(" ", "");
        this.nation = mnation.replaceAll(" ", "");
        this.sign_office = msign_office.replaceAll(" ", "");
        this.name = mname.replaceAll(" ", "");
        this.sign_data = msign_data.replaceAll(" ", "");
        this.birth_year = mbirth_year.replaceAll(" ", "");
        this.birth_month = mbirth_month.replaceAll(" ", "");
        this.birth_day = mbirth_day.replaceAll(" ", "");

        // 将参数封装进Data对象，然后转成json
        Data dataInfo = new Data();
        dataInfo.setAddress(address);
        dataInfo.setPhoto(photoHeard); // 图片
        dataInfo.setSex(sex);
        dataInfo.setIdcardno(id_num);
        dataInfo.setNation(nation); // 民族
        dataInfo.setGrantdept(sign_office);  // 签发机关
        dataInfo.setTo(to); // 有效期的开始时间
        dataInfo.setuSAMID("00000");
        dataInfo.setName(name);  // 名字
        dataInfo.setForm(from); // 有效期的截止日期
        dataInfo.setBorn(born); // 生日

        Gson gson = new Gson();
        // arraylist转json
        String data = gson.toJson(dataInfo);
        // 拼接串码json
        String chuanMa = "{\"reader_name\":\"" + bleNum + "\",\"reader_id\":\"" + bleId + "\",\"card_reader\":\""+bluetoothName+"\"}";
        Log.e("项目异常", "------chuanMa------" + chuanMa);
        Log.e("项目异常", "------bluetoothType------" + data);
        if (!mFlag) { // 补卡
            mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                    sign_office, name, sign_data, birth_year, birth_month, birth_day, photo, "", "", to,
                    from, born, photoHeard);
        } else { // 读卡
            data = Base64.encodeToString(data.getBytes(), Base64.DEFAULT);
            saveIDIcon(chuanMa, data, photoHeard);
        }
    }

    private void upLoadNet(final String bleNum, final String data, final String photoHeard) {
        App.getApp().getHttpTools().submitCardMsg(bleNum, data, new RequestCallBack() {
            @Override
            public void onSuccess(Object result) {
                Log.e("项目异常", "------upLoadNet身份证信息上传------" + result.toString());
                try {
                    Gson gson = new Gson();
                    IdInfo idInfo = gson.fromJson(result.toString(), IdInfo.class);
                    int code = idInfo.getStatus();
                    String msg = idInfo.getInfo();
                    if (code == 1) {
                        // 存储经办人状态值
                        PrefUtils.setString(mContext, "NEED_JBR", idInfo.getNeed_jbr());
                        // 成功监听
                        mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                                sign_office, name, sign_data, birth_year, birth_month, birth_day,
                                photo, filePhoto, idPath, to, from, born, photoHeard);
                    } else {
                        mOnUpLoadListener.onErrUpLoad(msg);
                    }
                } catch (Exception e) {
                    mOnUpLoadListener.onErrUpLoad("数据解析异常:" + e.toString());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mOnUpLoadListener.onErrUpLoad("网络或服务器错误");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 上传身份证照片
     */
    private void saveIDIcon(String bleNum, String data, final String photoHeard) {
        // 将身份证正面照转化为文件 photoHeard
        // String转bitmap

        try {
            Bitmap bitmap = BitmapAndStringUtils.convertStringToIcon(photoHeard);
            String namePath = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
            FileOutputStream b = null;
            File file = new File(App.getApp().getApplication().getCacheDir() + "/yw189imgae/");
            file.mkdirs();
            id_icon = App.getApp().getApplication().getCacheDir() + "/yw189imgae/" + namePath;
            b = new FileOutputStream(id_icon);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
            idPath = new File(id_icon).getPath();
            Log.e("项目异常", "---saveIDIcon---idPath------" + idPath);
            upLoadNet(bleNum, data, photoHeard);
            if (b != null) {
                b.flush();
                b.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("项目异常", "身份证头像保存到本地失败:" + e.toString());
            mOnUpLoadListener.onErrUpLoad("身份证头像保存到本地失败:" + e.toString());
        }
    }
}
